from flask import Flask, render_template, jsonify
import pandas as pd
import numpy as np
from datetime import datetime

app = Flask(__name__)

# 读取数据
def load_data():
    customer_base = pd.read_csv('customer_base.csv')
    customer_behavior = pd.read_csv('customer_behavior_assets.csv')
    return customer_base, customer_behavior

# 主页路由
@app.route('/')
def dashboard():
    return render_template('dashboard.html')

# API路由：获取顶部卡片数据
@app.route('/api/overview')
def get_overview():
    customer_base, customer_behavior = load_data()
    
    total_customers = len(customer_base)
    total_assets = customer_behavior['total_assets'].sum()
    active_users = len(customer_behavior[
        customer_behavior['app_login_count'] > 0
    ].customer_id.unique())
    
    return jsonify({
        'total_customers': total_customers,
        'total_assets': total_assets,
        'active_users': active_users
    })

# API路由：客户基础分布
@app.route('/api/customer_distribution')
def get_customer_distribution():
    customer_base, _ = load_data()
    
    age_groups = pd.cut(customer_base['age'], 
                       bins=[0, 25, 35, 45, 55, 65, 100],
                       labels=['25岁以下', '26-35岁', '36-45岁', '46-55岁', '56-65岁', '65岁以上'])
    
    age_dist = age_groups.value_counts().to_dict()
    gender_dist = customer_base['gender'].value_counts().to_dict()
    
    return jsonify({
        'age_distribution': age_dist,
        'gender_distribution': gender_dist
    })

# API路由：客户行为雷达图
@app.route('/api/customer_behavior')
def get_customer_behavior():
    _, customer_behavior = load_data()
    
    # 计算平均指标
    avg_behavior = {
        'app_login': customer_behavior['app_login_count'].mean(),
        'view_time': customer_behavior['app_financial_view_time'].mean(),
        'product_count': customer_behavior['product_count'].mean(),
        'investment_count': customer_behavior['investment_monthly_count'].mean(),
        'credit_expense': customer_behavior['credit_card_monthly_expense'].mean()
    }
    
    # 归一化数据到0-100
    max_values = {
        'app_login': 100,
        'view_time': 100,
        'product_count': 100,
        'investment_count': 100,
        'credit_expense': 100
    }
    
    normalized_behavior = {k: min(v * 100 / max_values[k], 100) 
                         for k, v in avg_behavior.items()}
    
    return jsonify(normalized_behavior)

# API路由：资产类型分布
@app.route('/api/asset_distribution')
def get_asset_distribution():
    _, customer_behavior = load_data()
    
    asset_columns = ['deposit_balance', 'financial_balance', 
                    'fund_balance', 'insurance_balance']
    
    asset_dist = customer_behavior[asset_columns].mean().to_dict()
    
    return jsonify(asset_dist)

# API路由：营销效果分析
@app.route('/api/marketing_effect')
def get_marketing_effect():
    _, customer_behavior = load_data()
    
    # 按月统计转化率
    monthly_conversion = customer_behavior.groupby('stat_month')['contact_result'].apply(
        lambda x: (x == 'success').mean()
    ).to_dict()
    
    return jsonify(monthly_conversion)

# API路由：高价值客户矩阵
@app.route('/api/high_value_customers')
def get_high_value_customers():
    _, customer_behavior = load_data()
    
    # 选择最近一个月的数据
    latest_month = customer_behavior['stat_month'].max()
    latest_data = customer_behavior[customer_behavior['stat_month'] == latest_month]
    
    # 准备散点图数据
    scatter_data = latest_data[[
        'total_assets', 
        'app_login_count',
        'product_count'
    ]].values.tolist()
    
    return jsonify(scatter_data)

if __name__ == '__main__':
    app.run(debug=True, port=5000)
